/**
 * useResetPasswordModal - 基于Element-Plus的纯组合式函数实现
 *
 * 完全通过组合式函数实现重置密码弹窗功能，无需额外组件
 *
 * @param {Object} app - Vue应用实例
 * @param {Object} options - 配置选项
 * @param {Object} options.api - API对象，需包含resetPassword方法
 * @param {Function} options.$t - 国际化函数
 * @param {Function} options.onReload - 重载回调函数
 * @param {string} options.title - 弹窗标题，默认'重置密码'
 * @param {string} options.width - 弹窗宽度，默认'600px'
 * @param {RegExp} options.passwordPattern - 密码强度正则表达式，默认/^.{6,}$/（至少6位）
 * @param {string} options.passwordErrorMessage - 密码强度验证失败时的错误信息
 * @returns {Object} 返回弹窗控制方法
 */

import { h, render, ref, nextTick } from 'vue';
import { ElDialog, ElForm, ElFormItem, ElInput, ElButton } from 'element-plus';

export function useResetPwdModal(app, options = {}) {
  const {
    api = null,
    $t = (key, defaultValue) => defaultValue || key,
    onReload = () => {},
    title = '重置密码',
    width = '600px',
    passwordPattern = null,
    passwordErrorMessage = null,
  } = options;

  // 响应式状态
  let isVisible = false;
  let container = null;
  let formRef = null;

  const loading = ref(false);
  const formData = ref({
    id: null,
    newPassword: '',
    confirmPassword: '',
  });

  // 创建密码强度验证函数
  const createPasswordValidator = (pattern, errorMessage) => {
    return (rule, value, callback) => {
      if (!value) {
        callback(
          new Error($t('menu.profile.validate.new_password', '请输入新密码')),
        );
        return;
      }

      // 使用传入的正则表达式进行验证
      if (pattern && !pattern.test(value)) {
        callback(
          new Error(
            errorMessage ||
              $t(
                'menu.profile.validate.password_strength',
                '密码强度不符合要求',
              ),
          ),
        );
        return;
      }

      callback();
    };
  };

  // 默认密码验证规则（至少6位）
  const defaultPasswordPattern = /^.{6,}$/;
  const defaultPasswordError = $t(
    'common.message.validate.min',
    '新密码至少需要6个字符',
    {
      field: $t('menu.profile.field.new_password', '新密码'),
      min: 6,
    },
  );

  // 获取密码验证函数
  const validatePasswordStrength = createPasswordValidator(
    passwordPattern || defaultPasswordPattern,
    passwordErrorMessage || defaultPasswordError,
  );

  // 密码匹配验证函数
  const validatePasswordMatch = (rule, value, callback) => {
    if (!value) {
      callback(
        new Error(
          $t('menu.profile.validate.confirm_password', '请输入确认密码'),
        ),
      );
    } else if (value !== formData.value.newPassword) {
      callback(
        new Error(
          $t('menu.profile.validate.not_match', '两次输入的密码不一致'),
        ),
      );
    } else {
      callback();
    }
  };

  // 表单验证规则
  const formRules = {
    newPassword: [
      {
        required: true,
        validator: validatePasswordStrength,
        trigger: 'blur',
      },
    ],
    confirmPassword: [
      {
        required: true,
        validator: validatePasswordMatch,
        trigger: 'blur',
      },
    ],
  };

  // 重置表单
  const resetForm = () => {
    if (formRef) {
      formRef.resetFields();
    }
    Object.assign(formData.value, {
      id: null,
      newPassword: '',
      confirmPassword: '',
    });
  };

  // 提交处理
  const handleSubmit = async () => {
    if (!formRef) return;

    try {
      await formRef.validate();
      loading.value = true;

      if (!api || typeof api !== 'function') {
        throw new Error('API对象或resetPassword方法未提供');
      }

      let password = formData.value.newPassword;

      const postData = {
        id: formData.value.id,
        password: password,
      };

      console.log('Reset Password Data:', postData);
      await api(postData);

      ElMessage.success($t('common.message.success', '操作成功'));

      resetForm();
      closeModal();
      onReload();
    } catch (error) {
      console.error('Error in reset password operation:', error);
    } finally {
      loading.value = false;
    }
  };

  // 取消处理
  const handleCancel = () => {
    resetForm();
    closeModal();
  };

  // 重置处理
  const handleReset = () => {
    resetForm();
  };

  // 创建表单内容
  const createFormContent = () => {
    return h(
      ElForm,
      {
        ref: (el) => {
          formRef = el;
        },
        model: formData.value,
        rules: formRules,
        labelWidth: '120px',
      },
      {
        default: () => [
          // 新密码字段
          h(
            ElFormItem,
            {
              label: $t('menu.profile.field.new_password', '新密码'),
              prop: 'newPassword',
            },
            {
              default: () =>
                h(ElInput, {
                  modelValue: formData.value.newPassword,
                  'onUpdate:modelValue': (value) => {
                    formData.value.newPassword = value;
                  },
                  type: 'password',
                  showPassword: true,
                  placeholder: $t(
                    'common.message.placeholder.general',
                    '请输入新密码',
                  ),
                }),
            },
          ),
          // 确认密码字段
          h(
            ElFormItem,
            {
              label: $t('menu.profile.field.confirm_password', '确认密码'),
              prop: 'confirmPassword',
            },
            {
              default: () =>
                h(ElInput, {
                  modelValue: formData.value.confirmPassword,
                  'onUpdate:modelValue': (value) => {
                    formData.value.confirmPassword = value;
                  },
                  type: 'password',
                  showPassword: true,
                  placeholder: $t(
                    'common.message.placeholder.general',
                    '请输入确认密码',
                  ),
                }),
            },
          ),
        ],
      },
    );
  };

  // 创建底部按钮
  const createFooter = () => {
    return [
      h(
        ElButton,
        {
          type: 'warning',
          onClick: handleCancel,
        },
        {
          default: () => $t('common.action.cancel', '取消'),
        },
      ),
      h(
        ElButton,
        {
          type: 'info',
          onClick: handleReset,
        },
        {
          default: () => $t('common.action.reset', '重置'),
        },
      ),
      h(
        ElButton,
        {
          type: 'primary',
          disabled: loading.value,
          onClick: handleSubmit,
        },
        {
          default: () => $t('common.action.confirm', '确定'),
        },
      ),
    ];
  };

  // 创建弹窗组件
  const createModal = () => {
    return h(
      ElDialog,
      {
        modelValue: isVisible,
        title: title,
        width: width,
        destroyOnClose: true,
        closeOnClickModal: false,
        closeOnPressEscape: true,
        showClose: true,
        draggable: true,
        'onUpdate:modelValue': (value) => {
          isVisible = value;
          if (!value) {
            closeModal();
          }
        },
        onClose: () => {
          closeModal();
        },
      },
      {
        default: () => createFormContent(),
        footer: () => createFooter(),
      },
    );
  };

  // 关闭弹窗
  const closeModal = () => {
    isVisible = false;
    if (container) {
      render(null, container);
      document.body.removeChild(container);
      container = null;
      formRef = null;
    }
  };

  // 渲染弹窗
  const renderModal = () => {
    if (container) {
      closeModal();
    }

    container = document.createElement('div');
    document.body.appendChild(container);

    const vnode = createModal();
    vnode.appContext = app._context;
    render(vnode, container);
  };

  // 显示弹窗
  const showModal = (id) => {
    isVisible = true;
    renderModal();

    nextTick(() => {
      resetForm();
      if (id) {
        formData.value.id = id;
      }
    });
  };

  // 返回控制方法
  return {
    showModal,
    closeModal,
    isVisible: () => isVisible,
    loading,
    formData,
  };
}

/**
 * 快速创建重置密码弹窗的便捷方法
 * @param {Object} app - Vue应用实例
 * @param {Object} api - API对象
 * @param {Function} $t - 国际化函数
 * @param {Function} onReload - 重载回调
 * @param {RegExp} passwordPattern - 可选，密码强度正则表达式
 * @param {string} passwordErrorMessage - 可选，密码强度验证失败时的错误信息
 * @returns {Object} 控制方法
 */
export const createResetPasswordModal = (
  app,
  api,
  $t,
  onReload,
  passwordPattern,
  passwordErrorMessage,
) => {
  return useResetPasswordModal(app, {
    api,
    $t,
    onReload,
    passwordPattern,
    passwordErrorMessage,
  });
};
